/**
* created by Lee on 2019/1/9 12:07
*/
$(function () {
	// localStorage.setItem("leaveDepartId",null);
	/* 鼠标右击操作 */
	document.oncontextmenu = function(){return false};     //禁止鼠标右键菜单显示
     var res = document.getElementById('costSetModal');      //找到id为box的div
     document.body.onmouseup = function(e){     //在body里点击触发事件
        if(e.button===2){       //如果button=1（鼠标左键），button=2（鼠标右键），button=0（鼠标中间键）
			// alert("e.offsetY:"+e.offsetY+",e.offsetX"+e.offsetX);
			var x=e.offsetX;
			var y=e.offsetY;
			
            res.style.top = '60%';     //鼠标点击时给div定位Y轴
            res.style.left ='10px';    //鼠标点击时给div定位X轴
            res.style.display = 'block';        //显示div盒子
        }else{
            // res.style.display = 'none';         //否则不显示div盒子
        }
        
    }
  //必要的数据
  //今天的年 月 日 ；本月的总天数；本月第一天是周几？？？
  var iNow = 0;
  var year = 0;
  var month = 0;
  var today = 0;
  var clickDay = 0; //点击了哪一天
  var todayJournal = "";
  var hasFestival = ""; //当天是否有节日

  function run(n) {

    var oDate = new Date(); //定义时间
    oDate.setMonth(oDate.getMonth() + n); //设置月份
    year = oDate.getFullYear(); //年
    month = oDate.getMonth(); //月
    today = oDate.getDate(); //日

    //公历节日
    var gregorianFestivals = {
      '0101': '元旦',
      '0214': '情人节',
      '0308': '妇女节',
      '0312': '植树节',
      '0401': '愚人节',
      '0501': '劳动节',
      '0504': '青年节',
      '0512': '护士节',
      '0601': '儿童节',
      '0701': '建党节',
      '0801': '建军节',
      '0910': '教师节',
      '1001': '国庆节',
      '1224': '平安夜',
      '1225': '圣诞节',
    };

    var lunarFestivals = {
      '腊月三十': '除夕',
      '正月初一': '春节',
      '正月十五': '元宵节',
      '五月初五': '端午节',
      '七月初七': '七夕节',
      '八月十五': '中秋节',
      '九月初九': '重阳节',
    }



    //计算本月有多少天
    var allDay = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];

    //判断闰年
    if (month == 1) {
      if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
        allDay = 29;
      }
    }

    //判断本月第一天是星期几
    oDate.setDate(1); //时间调整到本月第一天
    var week = oDate.getDay(); //读取本月第一天是星期几

    //console.log(week);
    $(".dateList").empty(); //每次清空
    //插入空白

    for (var i = 0; i < week; i++) {
      $(".dateList").append("<div class='each-date'></div>");
    }
	//临时保存的数组
	var chooseDays=[];
	//用户选择的日期(1倍工资)
	var chooseDays1=localStorage.getItem("chooseDays1");
	
	//用户选择的日期(2倍工资)
	var chooseDays2=localStorage.getItem("chooseDays2");
	
	//用户选择的日期(3倍工资)
	var chooseDays3=localStorage.getItem("chooseDays3");
	// departSetData(1);
	// alert(chooseDays3);
	//如果存在设置了倍数的数据，就显示说明
	if(chooseDays1.length>0 || chooseDays2.length>0 || chooseDays3.length>0){
		$("#costDesc").show();
	}
	if(chooseDays1==null || chooseDays1==""){
		chooseDays1=[];
	}else{
		chooseDays1=JSON.parse(localStorage.getItem("chooseDays1"));
	}
	if(chooseDays2==null || chooseDays2==""){
		chooseDays2=[];
	}else{
		chooseDays2=JSON.parse(localStorage.getItem("chooseDays2"));
	}
	if(chooseDays3==null || chooseDays3==""){
		chooseDays3=[];
	}else{
		chooseDays3=JSON.parse(localStorage.getItem("chooseDays3"));
	}
    //日期插入到dateList
    for (var i = 1; i <= allDay; i++) {
      hasFestival = "";
	  
	  var ifChoose1=0;
	  //设置1倍工资
	  for(var j=0;j<chooseDays1.length;j++){
		//如果是选中
		if(i==chooseDays1[j]){
			ifChoose1=1;
		}  
	  }
	  var ifChoose2=0;
	  //设置2倍工资
	  for(var j=0;j<chooseDays2.length;j++){
		  
	  	//如果是选中
	  	if(i==chooseDays2[j]){
	  		ifChoose2=1;
			// alert(ifChoose2);
	  	}	  
	  }
	  var ifChoose3=0;
	  //设置3倍工资
	  for(var j=0;j<chooseDays3.length;j++){
	  	//如果是选中
	  	if(i==chooseDays3[j]){
	  		ifChoose3=1;
	  	}	  
	  }
	
	 /* if(chooseDays1.length==0){
	  	$(".dateList").append("<div class='each-date date"+i+" ' id='calendar"+i+"'><span class='num'>" + i + "</span><span class='calendar'>" + festivalView(getLunarCalendar(i),month + 1,i) + "</span></div>");
	  		// return;
	  }else{
		 
	  } */
	  //1倍工资显示对应的日期
	  if(ifChoose1==1){
	     $(".dateList").append("<div class='each-date date"+i+" ' id='calendar"+i+"'><span class='num' style='background:#B5E2EE;border-radius: 50%;'>" + i + "</span><span class='calendar'>" + festivalView(getLunarCalendar(i),month + 1,i) + "</span></div>");
	  }else{
	  	//2倍工资显示对应的日期
	  	if(ifChoose2==1){
	  		$(".dateList").append("<div class='each-date date"+i+" ' id='calendar"+i+"'><span class='num' style='background:#F1C5BC;border-radius: 50%;'>" + i + "</span><span class='calendar'>" + festivalView(getLunarCalendar(i),month + 1,i) + "</span></div>");
	  	}else{
	  		//3倍工资显示对应的日期
	  		if(ifChoose3==1){
	  			$(".dateList").append("<div class='each-date date"+i+" ' id='calendar"+i+"'><span class='num' style='background:#C0B5EE;border-radius: 50%;'>" + i + "</span><span class='calendar'>" + festivalView(getLunarCalendar(i),month + 1,i) + "</span></div>");
	  		}else{
	  			$(".dateList").append("<div class='each-date date"+i+" ' id='calendar"+i+"'><span class='num'>" + i + "</span><span class='calendar'>" + festivalView(getLunarCalendar(i),month + 1,i) + "</span></div>");
	  		}
	  	}	
	  }/*  */
      // $(`.date${i}`).attr("festival",hasFestival)
    }
    //标记颜色=====================
    $(".dateList .each-date").each(function (i, elm) {
      var val = $(this).find(".num").text();
      //console.log(val);
      if (n == 0) {
        if (val < today) {
          $(this).addClass('gray')
        } else if (val == today) {
          $(this).children().first().addClass("pink")
        } else if (i % 7 == 0 || i % 7 == 6) {
          $(this).addClass('weekend')
        }
      } else if (n < 0) {
        $(this).addClass('gray')
      } else if (i % 7 == 0 || i % 7 == 6) {
        $(this).addClass('weekend')
      }
    });

    //定义标题日期
    $("#calendar .title").text(year + "年" + (month + 1) + "月");
	localStorage.setItem("calenderYear",year);
	localStorage.setItem("calenderMonth",(month+1));
	/* 每日最外层的点击事件 */
    $(".each-date").click(function () {
      clickDay = parseInt($(this).text());
      var pageDay = {
        year: year,
        month: month,
        date: clickDay
      };
      // console.log(pageDay);
      var detail = dateDetail({
        'timeStamp': new Date(pageDay.year, pageDay.month, pageDay.date).getTime()
      });
      // $("#journal").val(todayJournal);
	  // $(this).addClass('chooseDay');
	  // alert("选择的是:"+clickDay);
    });
	
	/* 每日阳历的点击事件 */
    $(".num").click(function () {
		layui.use(['element', 'layer'], function() {
		    var layer = layui.layer;
			 var departIds=localStorage.getItem("overtimeDepartId");
			 if(departIds==null || departIds==""){
			  	layer.alert("请先选择部门！", {icon: 5});
			  	return;
			 }
		});
	 var that=$(this);
	 clickDay = parseInt($(this).text());
	 var departIds=localStorage.getItem("overtimeDepartId");
	 if(departIds==null || departIds==""){
	  	return;
	 }
	 var pageDay = {
	   year: year,
	   month: month,
	   date: clickDay
	 };
	 // console.log(pageDay);
	 var detail = dateDetail({
	   'timeStamp': new Date(pageDay.year, pageDay.month, pageDay.date).getTime()
	 });
	 // $("#journal").val(todayJournal);
	 var ifExist=-1;
	 chooseDays.forEach(function(value,i){
	 		//新选择的日期，加入数组
	 		if(clickDay==value){
	 			ifExist=i;
	 			return;
	 		}
	 })
	 //如果该日期保存在其它工资组里面，要删除
	 chooseDays1.forEach(function(value,i){
	 	//新选择的日期，加入数组
	 	if(clickDay==value){
	 		chooseDays1.splice(i,1);
	 	}	
	 })
	 chooseDays2.forEach(function(value,i){
	 	//新选择的日期，加入数组
	 	if(clickDay==value){
	 		chooseDays2.splice(i,1);
	 	}	
	 })
	 chooseDays3.forEach(function(value,i){
	 	//新选择的日期，加入数组
	 	if(clickDay==value){
	 		chooseDays3.splice(i,1);
	 	}	
	 })
	 //第一次选中日期时
	 if(chooseDays.length==0){
	 	chooseDays.push(clickDay);
	 	$(this).addClass('chooseDay');
	 	$(this).css("color","#fff");
	 	$(this).css("background","#e45437");
	 	$(this).css("border","none");	  
	 }else{
	 	if(ifExist==-1){
	 		chooseDays.push(clickDay);
	 		$(this).addClass('chooseDay');
	 		$(this).css("color","#fff");
	 		$(this).css("background","#e45437");
	 		$(this).css("border","none");
	 		// alert('forEach遍历:'+clickDay+'--'+value);
	 	}
	 	//之前存在的日期，取消，数组中删除
	 	else{
	 		// alert("ifExist:"+ifExist);
	 		chooseDays.splice(ifExist,1);
	 		$(this).removeClass('chooseDay');
	 		$(this).css("color","#333");
	 		$(this).css("background","#F6F6F6");
	 		$(this).css("border-radius","50%");
	 		$(this).css("border","none");
	 	}	  
	 }
	  // alert("数组个数："+chooseDays.length);
	  // alert("选择的是:"+clickDay);
    });
	/* 设置1倍费用 */
	$("#costSet1").click(function () {
		layui.use(['element', 'layer'], function() {
		    var layer = layui.layer;
			// alert("1数组个数："+chooseDays.length);
		    chooseDays1=chooseDays;
			chooseDays=[];
		   var departIds=localStorage.getItem("overtimeDepartId");
		   if(departIds==null || departIds==""){
		    	layer.alert("请选择部门！", {icon: 5});
		    	return;
		   }
		   
		   var data = [];
		   for(var i=0;i<chooseDays1.length;i++){
				var day=chooseDays1[i];
				if(day<10){
					day="0"+day;
				}
				var newMonth="";
				if((month+1)<10){
					newMonth="0"+(month+1);
				}
				var param = {
					deptId:departIds,
					overtimeDate:year+"-"+newMonth+"-"+day,
					multiple:1
				}
				data.push(param);
		   }
			   
		   var userToken = localStorage.getItem("userToken");
		   $.ajax({
				type:"POST",
				url:site_url+"/deptfeemultiples/list",
				ataType:"json",
				contentType:"application/json",
				headers:{'token':userToken},
				data: JSON.stringify(data),
				success:function(obj){
					console.log(obj)
					if(obj.code==0){
						 // layer.alert("您设置了1倍工资！", {icon: 6});
						 $("#costSetModal").hide();
						 setCost();
					}else{
						layer.alert("保存失败！", {icon: 5});
					}
				}
			});
		});
	  
	});
	/* 设置2倍费用 */
	$("#costSet2").click(function () {
	  layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
		// alert("2数组个数："+chooseDays.length);
		chooseDays2=chooseDays;
		chooseDays=[];
		var departIds=localStorage.getItem("overtimeDepartId");
		if(departIds==null || departIds==""){
		 	layer.alert("请选择部门！", {icon: 5});
		 	return;
		}
		
		var data = [];
	
		for(var i=0;i<chooseDays2.length;i++){
			var day=chooseDays2[i];
			if(day<10){
				day="0"+day;
			}
			var newMonth="";
			if((month+1)<10){
				newMonth="0"+(month+1);
			}
			var param = {
				deptId:departIds,
				overtimeDate:year+"-"+newMonth+"-"+day,
				multiple:2
			}
			data.push(param);
		}
		
		var userToken = localStorage.getItem("userToken");
		$.ajax({
			type:"POST",
			url:site_url+"/deptfeemultiples/list",
			ataType:"json",
			contentType:"application/json",
			headers:{'token':userToken},
			data: JSON.stringify(data),
			success:function(obj){
				console.log(obj)
				if(obj.code==0){
					 // layer.alert("您设置了2倍工资！", {icon: 6});
					 $("#costSetModal").hide();
					 setCost();
				}else{
					layer.alert("保存失败！", {icon: 5});
				}
			}
		});
	  });
	});
	/* 设置3倍费用 */
	$("#costSet3").click(function () {
	  layui.use(['element', 'layer'], function() {
			var layer = layui.layer;
			// alert("3数组个数："+chooseDays.length);
			chooseDays3=chooseDays;
			chooseDays=[];
			var departIds=localStorage.getItem("overtimeDepartId");
			if(departIds==null || departIds==""){
			 	layer.alert("请选择部门！", {icon: 5});
			 	return;
			}
			
			var data = [];
			
			for(var i=0;i<chooseDays3.length;i++){
				var day=chooseDays3[i];
				if(day<10){
					day="0"+day;
				}
				var newMonth="";
				if((month+1)<10){
					newMonth="0"+(month+1);
				}
				var param = {
					deptId:departIds,
					overtimeDate:year+"-"+newMonth+"-"+day,
					multiple:3
				}
				data.push(param);
			}
			
			var userToken = localStorage.getItem("userToken");
			$.ajax({
				type:"POST",
				url:site_url+"/deptfeemultiples/list",
				ataType:"json",
				contentType:"application/json",
				headers:{'token':userToken},
				data: JSON.stringify(data),
				success:function(obj){
					console.log(obj)
					if(obj.code==0){
						 // layer.alert("您设置了3倍工资！", {icon: 6});
						 $("#costSetModal").hide();
						 setCost();
					}else{
						layer.alert("保存失败！", {icon: 5});
					}
				}
			});
	  });
	});
	/* 保存设置费用 */
	function setCost(){
		localStorage.setItem("chooseDays1",JSON.stringify(chooseDays1));
		localStorage.setItem("chooseDays2",JSON.stringify(chooseDays2));
		localStorage.setItem("chooseDays3",JSON.stringify(chooseDays3));
		run(0);
	}
	
	/* 加班费用的保存按钮 */
	$("#costSave").click(function () {
	  layui.use(['element', 'layer'], function() {
	    var layer = layui.layer;
	  	var overtime=$('#overtime').val();  //加班时间
	  	var departIds=localStorage.getItem("overtimeDepartId");
	  	// alert(departIds);
	  	if(departIds==null || departIds==""){
	  	 	layer.alert("请选择部门！", {icon: 5});
	  	 	return;
	  	}
	  	if(overtime=="" || overtime<=0){
	  		layer.alert("加班时间不能为空或负数！", {icon: 5});
	  		return;
	  	}
	 
		setCost();
		var overtimeId=localStorage.getItem("overtimeId");
		var data = {
			id:overtimeId,
			unitPrice:overtime,
			deptId:localStorage.getItem("overtimeDepartId"),
			// id:id
		}
		
		var userToken = localStorage.getItem("userToken");
		$.ajax({
			type:"POST",
			url:site_url+"/deptovertimefees",
			ataType:"json",
			contentType:"application/json",
			headers:{'token':userToken},
			data: JSON.stringify(data),
			success:function(obj){
				console.log(obj)
				if(obj.code==0){
					localStorage.setItem("overtimeId","");
					layer.alert("加班费用设置成功！", {icon: 6});
				}else{
					layer.alert("保存失败！", {icon: 5});
				}
			}
		});
	  });
	});
    /**
     * 获取农历
     */
    function getLunarCalendar(date) {
      let detail = dateDetail({
        'timeStamp': new Date(year, month, date).getTime()
      }).aL.lunarCalendar;
      // return [detail.slice(0, 2),detail.slice(2, 4)]
      return detail
    }

    /**
     * 获取当日是否是农历假日
     */
    function festivalView(lunarCalendar,month,date) {
      if(Object.keys(lunarFestivals).indexOf(lunarCalendar) != -1) {
        hasFestival = lunarFestivals[lunarCalendar]
        return lunarFestivals[lunarCalendar]
      } else {
        let day = ( month > 9 ? month + '' : "0" + month) + ( date > 9 ? date + '' : "0" + date);
        if(Object.keys(gregorianFestivals).indexOf(day) != -1) {
          hasFestival = gregorianFestivals[day]
          return gregorianFestivals[day]
        }else {
          return lunarCalendar.slice(2, 4)
        }
      }
    }

    /**
     * 滚动页面时防止tip定位出错
     */
    var contentTop = document.getElementById("content").getBoundingClientRect().top;
    var scrollTop = contentTop > 0 ? 0 : document.documentElement.scrollTop;
    window.onscroll = function() {
      contentTop = document.getElementById("content").getBoundingClientRect().top;
      scrollTop = contentTop > 0 ? 0 : document.documentElement.scrollTop;
    };

    var x = 10;
    var y = 20;
    $(".each-date").mouseenter(function (e) {
      let date = $(this).find(".num").text();
      if (date) {
        let journal = window.localStorage.getItem("yyJournal");
        let obj = journal?JSON.parse(journal):{};
        todayJournal = "";
        let day = new Date(year,month,date).getTime() + '';
        if(obj && Object.keys(obj).indexOf(day) != -1) {
          todayJournal = obj[day];
        }
        let arr = "鼠牛虎兔龙蛇马羊猴鸡狗猪".split(/(?!\b)/);
        let todayMsg = dateDetail({
          'timeStamp': new Date(year, month, date).getTime()
        });
        let festival = $(this).attr("festival");
        if(festival) {
          $(".festival-content").show();
          $(".festival-icon").show();
          $(".tip-today").html(festival);
        } else {
          if (n == 0 && date == today) {
            $(".festival-content").show();
            $(".festival-icon").hide();
            $(".tip-today").html("今日");
          } else {
            $(".festival-content").hide();
          }
        }
        $("#tip .tip-week").html(todayMsg.week);
        $("#tip .tip-weekEng").html(todayMsg.weekEng);
        $("#tip .tip-annals").html(todayMsg.aL.annals);
        $("#tip .zodiac").html(arr[(year - 1912) % 12]);
        $("#tip .tip-lunarCalendar").html("农历" + todayMsg.aL.lunarCalendar);
        if(todayJournal) {
          $(".journal-msg").html(todayJournal);
          $(".tip-journal").show();
        } else {
          // $(".journal-msg").html("点击添加日志");
          $(".tip-journal").hide();
        }
        $("#tip").css({
          "top": (e.pageY - scrollTop + y) + "px",
          "left": (e.pageX + x) + "px"
        }).show(); //设置x坐标和y坐标，并且显示
      }
    }).mousemove(function (e) {
      if(e.pageX + x + 300 >= document.body.clientWidth) {
        $("#tip").css({
          "top": (e.pageY - scrollTop + y) + "px",
          "left": (e.pageX - 200) + "px"
        }); //设置x坐标和y坐标，并且显示
      } else {
        $("#tip").css({
          "top": (e.pageY - scrollTop + y) + "px",
          "left": (e.pageX + x) + "px"
        });
      }
    }).mouseleave(function () {
      $("#tip").hide(); //移除
    });
	/* 弹出框的保存 */
    $(".btn-primary").click(function () {
      let journal = $("#journal").val();
      let day = new Date(year,month,clickDay).getTime();
      yyJournal = window.localStorage.getItem("yyJournal");
      let obj = yyJournal?JSON.parse(yyJournal):{};
      obj[day] = journal;
      window.localStorage.setItem('yyJournal',JSON.stringify(obj))
    })
  };


  /* 费用数据 */
  function calDepartSetData(iNow){
  	var departIds="";
  	var name="";
  	var num=0;
  	departIds=localStorage.getItem("overtimeDepartId");
  	name=localStorage.getItem("overtimeDepartName");
  	num=1;
  	if(departIds==null || departIds=="null" || departIds==""){
  		// $("#sys-depart-data").html("您还没有选择部门");
  		setStaffNull();
  		return;
  	}
  	var userToken = localStorage.getItem("userToken");
  	var year=localStorage.getItem("calenderYear");
  	var month=localStorage.getItem("calenderMonth");
  	// alert("年："+year+",月："+month);
  	$.ajax({
  		url:site_url+"/deptovertimefees/dept/"+departIds,
  		dataType:'json',
  		type:"GET",
  		headers:{'token':userToken},
  		success:function(data){
  			$("#overtime").val(data.data.unitPrice)
  			
  			$.ajax({
  				url:site_url+"/deptfeemultiples?deptId="+departIds+"&overtimeDate="+(year+"-"+month),
  				dataType:'json',
  				type:"GET",
  				headers:{'token':userToken},
  				success:function(data){
  					var data=data.data;
  					var chooseDays1=[];
  					var chooseDays2=[];
  					var chooseDays3=[];
  					var multiple=0;
  					var date="";
  					//获取日(最后一个"-"到最后一个字符之间)
  					var day="";
  					for(var i=0;i<data.length;i++){
  						multiple=data[i].multiple;
  						date=data[i].overtimeDate;
  						//获取日(最后一个"-"到最后一个字符之间)
  						day=date.substring(date.lastIndexOf('-')+1,date.length);
  						// alert("multiple="+multiple+",day="+day);
  						if(multiple==1){
  							chooseDays1.push(day);
  						}else if(multiple==2){
  							chooseDays2.push(day);
  						}else if(multiple==3){
  							chooseDays3.push(day);
  						}
  					}
  					if(data.length>0){
  						if(chooseDays1!=""){
  							localStorage.setItem("chooseDays1",JSON.stringify(chooseDays1));
  						}else{
  							localStorage.setItem("chooseDays1","");
  						}
  						if(chooseDays2!=""){
  							localStorage.setItem("chooseDays2",JSON.stringify(chooseDays2));
  						}else{
  							localStorage.setItem("chooseDays2","");
  						}
  						if(chooseDays3!=""){
  							localStorage.setItem("chooseDays3",JSON.stringify(chooseDays3));
  						}else{
  							localStorage.setItem("chooseDays3","");
  						}
  						// $().calender();
  					}else{
  						localStorage.setItem("chooseDays1","");
  						localStorage.setItem("chooseDays2","");
  						localStorage.setItem("chooseDays3","");
  					}
					run(iNow);
  					console.log(data)
  				}
  			})
  		}
  	})
  	if(departIds==null || departIds=="null" || departIds==""){
  		setStaffNull();
  		return;
  	}
  	
  	$("#sys-depart-data").html("");
  	var html='';
  	html+='<div class="sys-depart-item" id="departId'+departIds+'">';
  	html+='<div class="sys-depart-item-top">';
  	html+='<img class="sys-depart-item-img" src="img/sys_depart_icon.png" />';
  	html+='<label>'+name+'</label>';
  	html+='</div>';
  	html+='</div>';
  	$("#sys-depart-data").html(html);
  }
  $.fn.calender = function(){
	
  }; 
 run(0);
  $(".a1").click(function () {
    iNow--;
    run(iNow);
	var departIds=localStorage.getItem("overtimeDepartId");
	// alert(departIds);
    $("#calendar .calendar-bg").css("background-image", `url("img/${month}.jpg")`)
    $(".calendarImg").css("background-image", `url("img/${month}.jpg")`)
	calDepartSetData(iNow);
  });

  $(".a2").click(function () {
    iNow++;
    run(iNow);
    $("#calendar .calendar-bg").css("background-image", `url("img/${month}.jpg")`)
    $(".calendarImg").css("background-image", `url("img/${month}.jpg")`)
	calDepartSetData(iNow);
  });

});
